<?php

namespace app\admin\controller;
use app\admin\model\MiningSpecification as MiningSpecificationModel;

class MiningSpecification extends Admin
{
    private $postField = 'pid,name,e_name,t_name,label,e_label,t_label,pic,e_pic,t_pic,money,max_possess,duration,daily_release,status';
    function index(){
        if(empty($this->request->post())){
            return view('index');
        }else{
            $limit  = $this->request->post('limit', 20, 'intval');
            $page = $this->request->post('page', 1, 'intval');
            $order  = $this->request->post('order', '', 'serach_in');	//排序字段
            $sort  = $this->request->post('sort', '', 'serach_in');		//排序方式
            $where = [];

            $orderby = ($sort && $order) ? $sort.' '.$order : 'id desc';
            //获取用户等级列表
            $res = MiningSpecificationModel::getList($orderby,$limit,$page,formatWhere($where));

            $data['status'] = 200;
            $data['data'] = $res;
            return json($data);

        }
    }

    /**
     * 添加矿机
     * @return \think\response\Json
     */
    function add(){
        $data = $this->request->only(explode(',',$this->postField),'post',null);
        $data['add_time'] = date('Y-m-d H:i:s',time());
        $data['update_time'] = date('Y-m-d H:i:s',time());

        $res = MiningSpecificationModel::insertGetId($data);

        if(empty($res)) return json(['status'=>200,'data'=>$res,'msg'=>'添加失败']);
        return json(['status'=>200,'data'=>$res,'msg'=>'添加成功']);
    }

    /**
     * 获取该矿机详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getEdit(){
        $id =  $this->request->post('id', '', 'serach_in');
        if(!$id) throw new ValidateException ('参数错误');
        $res = MiningSpecificationModel::getDetails($id);
        return json(['status'=>200,'data'=>$res]);
    }

    /**
     * 修改矿机
     * @return \think\response\Json
     */
    function edit(){
        $postField = $this->postField.',id';
        $data = $this->request->only(explode(',',$postField),'post',null);
        MiningSpecificationModel::where('id',$data['id'])->update($data);
        return json(['status'=>200,'msg'=>'修改成功']);
    }

    /**
     * 删除矿机
     * @return \think\response\Json
     */
    function delete(){
        $idx =  $this->request->post('id', '', 'serach_in');
        if(!$idx) throw new ValidateException ('参数错误');
        MiningSpecificationModel::destroy(['id'=>explode(',',$idx)],true);
        return json(['status'=>200,'msg'=>'操作成功']);
    }
}